from django.contrib.auth.backends import ModelBackend

from users.models import User


class MyModelBackend(ModelBackend):
    # 重写一下  authenticate
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 验证用户名和密码, 或者手机号和密码, 如果有任何一个验证通过, 就返回user对象
        # 如果没有验证通过, 就返回None

        try:
            user = User.objects.get(mobile=username)
        except Exception as e:
            try:
                user = User.objects.get(username=username)
            except Exception as e:
                return None

        # 验证密码 使用user对象的checkpassword 方法
        if user.check_password(raw_password=password):
            # 如果用户密码验证通过, 就返回user对象
            return user
        else:
            return None
